<template>
  <div class="buycar">
    <MyList :getList="getList" :resetList="resetList">
      <van-card v-if="list.length" v-for="item in list" :key="item.id" :desc="item.msg" :title="item.title">
        <template #thumb>
          <van-checkbox v-model="item.checked" @change="onChangOne" style="margin-right: 5px;" />
          <img :src="item.imgList[0]?.url" width="92">
        </template>
        <template #price>
          <div class="pricebar">
            <span>￥<span class="price">{{ item.price?.toFixed(2) }}</span></span>
            <van-stepper v-model="item.value" min="1" max="10" integer @change="changeCar(item)" />
          </div>
        </template>
      </van-card>
      <van-empty v-else />
    </MyList>
    <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit" v-if="list.length">
      <van-checkbox v-model="checkedAll" @click="onChangAll">全选</van-checkbox>
      <a class="del" @click="onDel">删除</a>
    </van-submit-bar>
  </div>
</template>
<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted } from 'vue';
import MyList from "@/components/myList/index.vue"
import { toPage, isWeiXin, reLaunch } from '@/utlis/tools';
import { showToast, showConfirmDialog } from "vant"
import { getBuyCar, modifyBuyCar, delBuyCar } from "@/api/index"
import { useStore } from "@/store"
import Tools from '@/utlis/tools';
const store = useStore();
const router = useRouter()
const iswx = ref(isWeiXin())
const checkedAll = ref(false)
const totalPrice = ref(0)
const sum = ref(0)
const list = ref([
  // {
  //   id: 1,
  //   title: "商品名称",
  //   msg: "商品描述商品描述",
  //   img: "https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg",
  //   price: 30,
  //   value: 1,
  //   checked: false,
  // },
])
const selectList = ref([])

onMounted(() => {
  let token = window.localStorage.getItem("token");
  if (!token) {
    showToast("请先登录")
    router.push("/me?istoken=1");
    return
  }
  // getList(1, "1")
})
const resetList = () => {
  list.value = []
}
const getList = async (index, tag) => {
  if (store.istoken) {
    const { data, code, paginate } = await getBuyCar({
      page: index ? index : 1,
      size: 10,
    })
    if (code == 200) {
      let arr = data.map(item => {
        item.imgList = JSON.parse(item.imgList)
        return item
      })
      tag ? list.value = arr : list.value.push(...arr)
      return {
        total: paginate.total,
        list: list.value
      }
    } else {
      return {
        total: list.value.length,
        list: list.value
      }
    }
  } else {
    return {
      total: list.value.length,
      list: list.value
    }
  }
}
const changeCar = async (item) => {
  calc()
  await modifyBuyCar({
    id: item._id,
    title: item.title,
    msg: item.msg,
    img: item.img,
    price: item.price,
    value: item.value,
  })
  // getList(1, "1")
}
const onChangAll = () => {
  list.value.map(item => item.checked = checkedAll.value)
  calc()
}
const onChangOne = () => {
  let flag = list.value.every(item => item.checked == true)
  checkedAll.value = flag
  calc()
}
const calc = () => {
  let arr = list.value.filter(item => item.checked == true)
  selectList.value = arr.map(item => {
    item.ordernum = Tools.getUid()
    item.status = "a"
    return item
  })
  let price = 0
  let num = 0
  arr.map(item => {
    num += item.value
    let p = item.price * item.value
    price += p
  })
  totalPrice.value = price * 100
  sum.value = num
}
const onSubmit = () => {
  if (sum.value <= 0) {
    showToast("请至少选择一件商品")
    return
  }
  console.log(selectList.value);
  router.push({
    name: `orderdetail`,
    query: {
      totalPrice: totalPrice.value / 100,
      sum: sum.value,
      selectList: JSON.stringify(selectList.value)
    }
  })
  // checkedAll.value = false
};
const onDel = async () => {
  if (sum.value <= 0) {
    showToast("请至少选择一件商品")
    return
  }
  showConfirmDialog({
    title: '删除购物车',
    message: '确定删除？',
  }).then(async () => {
    // let arr = list.value.filter(item => item.checked == true)
    let brr = selectList.value.map(item => item._id)
    console.log(brr);
    await delBuyCar({ id: brr.join(",") })
    getList(1, "1")
  })
  // checkedAll.value = false
}


</script>
<style lang="less" scoped>
.buycar {
  overflow: auto;
  height: calc(100vh - 130px);
  padding: 15px;
  padding-top: 20px;

  /deep/.van-submit-bar__button--danger {
    background: #1989fa;
  }

  .del {
    margin-left: 25px;
    color: #1989fa;
  }

  /deep/.van-card__price {
    width: 100%;
  }

  /deep/.van-card__thumb {
    display: flex;
    align-items: center;
    width: inherit;
  }

  .pricebar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #f00;

    .price {
      font-size: 18px;
    }
  }

  /deep/ .van-ellipsis {
    white-space: inherit;
    max-height: none;
  }

  /deep/.van-submit-bar {
    bottom: 70px;
  }
}
</style>
